package com.rongc.client.freight.base.view.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.rongc.client.core.network.code.HandleCode;
import com.rongc.client.core.network.http.RequestManager;
import com.rongc.client.core.utils.ActivityUtils;
import com.rongc.client.core.utils.LogUtils;
import com.rongc.client.core.utils.StringUtils;
import com.rongc.client.core.utils.SystemUtil;
import com.rongc.client.freight.ApiUrl;
import com.rongc.client.freight.R;
import com.rongc.client.freight.UniApplication;
import com.rongc.client.freight.base.BaseFragment;
import com.rongc.client.freight.base.model.BaseDic;
import com.rongc.client.freight.base.model.UserBean;
import com.rongc.client.freight.base.request.result.UserResult;
import com.rongc.client.freight.base.view.activity.LoginActivity;
import com.rongc.client.freight.base.view.adapter.RecyclerBaseAdapter;
import com.rongc.client.freight.base.view.adapter.RecyclerMineAdapter;
import com.rongc.client.freight.base.view.widget.CircleImageView;
import com.rongc.client.freight.base.view.widget.SpaceItemDecoration;
import com.rongc.client.freight.business.mine.request.api.UserInfoApi;
import com.rongc.client.freight.business.mine.view.activity.AuthHostActivity;
import com.rongc.client.freight.business.mine.view.activity.CarHostActivity;
import com.rongc.client.freight.business.mine.view.activity.CommentActivity;
import com.rongc.client.freight.business.mine.view.activity.InviteActivity;
import com.rongc.client.freight.business.mine.view.activity.MarkActivity;
import com.rongc.client.freight.business.mine.view.activity.MineScoreActivity;
import com.rongc.client.freight.business.mine.view.activity.MineWalletActivity;
import com.rongc.client.freight.business.mine.view.activity.PasswordPayActivity;
import com.rongc.client.freight.business.mine.view.activity.SettingActivity;
import com.rongc.client.freight.business.mine.view.activity.ShopActivity;
import com.rongc.client.freight.utils.UserUtils;
import com.rongc.client.freight.utils.UtilMethod;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Bruce on 2016/11/24.
 */
public class MineFragment extends BaseFragment implements View.OnClickListener{
    @Bind(R.id.recycler)
    RecyclerView recyclerView;
    @Bind(R.id.iv_header)
    CircleImageView mIvHead;
    @Bind(R.id.tv_name)
    TextView mTvName;
    @Bind(R.id.tv_tip)
    TextView mTvTip;
    @Bind(R.id.tv_wallet)
    TextView mTvWallet;
    @Bind(R.id.tv_integral)
    TextView mTvIntegral;

    UserBean userBean;
    RecyclerMineAdapter mRecyclerAdapter;

    List<String> lsOperate;
    SpaceItemDecoration itemDecoration ;

    Response.Listener<UserResult> respOrderListener = new Response.Listener<UserResult>() {

        @Override
        public void onResponse(UserResult response) {
            if (HandleCode.requestSuccess()) {
                UserUtils.makeUser(response);
                showView();
            } else {
                UtilMethod.dismissProgressDialog(getActivity());
            }
        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            LogUtils.i("error.getMessage(): " + error.getMessage());
            UtilMethod.dismissProgressDialog(getActivity());
        }
    };

    @OnClick({R.id.tv_wallet,R.id.tv_integral,R.id.iv_header})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_wallet:
                if(StringUtils.isNotEmpty(UniApplication.getInstance().getUserInfo().getPayPwd())) {
                    ActivityUtils.startActivity(getActivity(), MineWalletActivity.class);
                }else{
                    ActivityUtils.startActivity(getActivity(), PasswordPayActivity.class);
                }
                break;
            case R.id.tv_integral:
                ActivityUtils.startActivity(getActivity(), MineScoreActivity.class);
                break;
            case R.id.iv_header:
                Intent intent = new Intent(getActivity(), SettingActivity.class);
                startActivityForResult(intent,11);
                break;
        }
    }

    @Override
    public void initData() {

        lsOperate.add(BaseDic.MineType.AUTH_TYPE);
        lsOperate.add(BaseDic.MineType.SHOP_TYPE);
        lsOperate.add(BaseDic.MineType.CAR_TYPE);
//        lsOperate.add(BaseDic.MineType.CHECK_IN_TYPE);
        lsOperate.add(BaseDic.MineType.COMMENT_TYPE);
        lsOperate.add(BaseDic.MineType.SETTING_TYPE);
//        lsOperate.add(BaseDic.MineType.INVITE_TYPE);

        RequestManager.getInstance().call(new UserInfoApi(new UserInfoApi.UserInfoParams(),
                respOrderListener, errorListener));

    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.menu_contact, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_contact:
                ActivityUtils.callToContact(getActivity());
//                ActivityUtils.startActivity(getActivity(), ContactActivity.class);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            if(data != null && data.getBooleanExtra("quit",false)){
                ActivityUtils.startActivity(getActivity(), LoginActivity.class);
                getActivity().finish();
                System.exit(0);
            }else{
                RequestManager.getInstance().call(new UserInfoApi(new UserInfoApi.UserInfoParams(),
                        respOrderListener, errorListener));
            }
        }
    }

    @Override
    public void initListener() {
        mRecyclerAdapter.setOnItemClickListener(new RecyclerBaseAdapter.OnItemClickListener<String>() {
            @Override
            public void onItemClick(View view, int position, String data) {
                switch (data){
                    case BaseDic.MineType.AUTH_TYPE:
                        ActivityUtils.startActivity(getActivity(), AuthHostActivity.class);
                        break;
                    case BaseDic.MineType.SHOP_TYPE:
                        ActivityUtils.startActivity(getActivity(), ShopActivity.class);
                        break;
                    case BaseDic.MineType.CAR_TYPE:
                        if(BaseDic.IdentityType.DRIVING_TYPE.equals(UniApplication.getInstance().getType()))
                            ActivityUtils.startActivity(getActivity(), CarHostActivity.class);
                        else
                            ActivityUtils.toast("货主不能发布车辆");
                        break;
                    case BaseDic.MineType.CHECK_IN_TYPE:
                        ActivityUtils.startActivity(getActivity(), MarkActivity.class);
                        break;
                    case BaseDic.MineType.COMMENT_TYPE:
                        ActivityUtils.startActivity(getActivity(), CommentActivity.class);
                        break;
                    case BaseDic.MineType.INVITE_TYPE:
                        ActivityUtils.startActivity(getActivity(), InviteActivity.class);
                        break;
                    case BaseDic.MineType.SETTING_TYPE:
                        Intent intent = new Intent(getActivity(), SettingActivity.class);
                        startActivityForResult(intent,11);
                        break;
                }
            }
        });
    }

    void showView(){
        userBean = UniApplication.getInstance().getUserInfo();
        Glide.with(UniApplication.getInstance())
                .load(ApiUrl.getImgUrl(userBean.getHead()))
                .asBitmap()
                .centerCrop()
                .placeholder(R.mipmap.universal_head_default)
                .into(new BitmapImageViewTarget(mIvHead) {
                    @Override
                    protected void setResource(Bitmap resource) {
                        RoundedBitmapDrawable roundedBitmapDrawable =
                                RoundedBitmapDrawableFactory.create(getResources(), resource);
                        roundedBitmapDrawable.setCircular(true);
//                                        roundedBitmapDrawable.setCornerRadius(20); //设置圆角半径（根据实际需求）
                        roundedBitmapDrawable.setAntiAlias(true); //设置反走样
                        getView().setImageDrawable(roundedBitmapDrawable);
                    }
                });

        mTvName.setText(StringUtils.getName(userBean.getNickname(),userBean.getPhone()));

        switch (UniApplication.getInstance().getType()){
            case BaseDic.IdentityType.DRIVING_TYPE:
                mTvTip.setText(String.format(
                        getContext().getResources().getString(R.string.mine_tip_driver),
                        userBean.getCountJD(),userBean.getCountWY()));

                break;
            case BaseDic.IdentityType.OWNER_TYPE:
                mTvTip.setText(String.format(
                        getContext().getResources().getString(R.string.mine_tip_owner),
                        userBean.getCountXD(),userBean.getCountWY()));

                break;
        }


        mTvIntegral.setText(Html.fromHtml(String.format(
                getContext().getResources().getString(R.string.mine_integral_title),
                userBean.getIntegral())));

        mTvWallet.setText(Html.fromHtml(String.format(
                getContext().getResources().getString(R.string.mine_wallet_title),
                userBean.getBalance())));
    }

    @Override
    public void initView() {
        Toolbar toolbar = initToolbar("");
        /*TextView textView = (TextView) toolbar.findViewById(R.id.toolbar_title);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SettingActivity.class);
                startActivityForResult(intent,11);
//                ActivityUtils.startActivityForResult(getActivity(), SettingActivity.class,11);
            }
        });*/



        lsOperate = new ArrayList<>();
        mRecyclerAdapter = new RecyclerMineAdapter(getActivity(),lsOperate);

        if(itemDecoration == null)
            itemDecoration = new SpaceItemDecoration(SystemUtil.dip2px(getContext(), 1f), SystemUtil.dip2px(getContext(), 1f));

        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
        recyclerView.removeItemDecoration(itemDecoration);
        recyclerView.addItemDecoration(itemDecoration);
        recyclerView.setAdapter(mRecyclerAdapter);

        showView();

    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_host_mine;
    }
}
